﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;


namespace CodeReplace
{
    public partial class Form1 : Form
    {
        public Tools T = new Tools();
        public String[] OpendFilesName; // 所有载入的文件名称

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_DragDrop(object sender, DragEventArgs e)
        {
            string filesName = T.dragDrop(e);      //拖入窗体的文件放下
            OpendFilesName = filesName.Split(';'); //分割为所有的文件名

            label3.Text = "载入文件总数：" + OpendFilesName.Length;
        }

        private void Form1_DragEnter(object sender, DragEventArgs e)
        {
            T.dragEnter(e);
        }

        /// <summary>
        /// 执行字符串替换逻辑
        /// </summary>
        private void button1_Click(object sender, EventArgs e)
        {
            //String data = "int[] ids = { R.id.music, R.id.about, R.id.more, R.id.help /* , R.id.CDKey */};";
            //String data = "findViewById(R.id.mem_6);";

            //String data = "				btn.setBackgroundResource(R.drawable.shengyinx);";
            //String from = "R.drawable.*", to = "R.drawable(\"*\")";

            //data = replace(data, from, to);
            //MessageBox.Show("替换逻辑完成!\n" + data);


            String data = "";
            foreach (String fileName in OpendFilesName)
            {
                //String data = T.ToString(fileName);
                data = T.ToString(fileName);
                data = replaceLogic(data, textBox1.Text.Trim(), textBox2.Text.Trim());

                //MessageBox.Show("替换逻辑完成!\n" + data);
                T.SaveToNativeFile(data, fileName, true);
            }
            MessageBox.Show("替换逻辑完成!");
        }

        // R.id.*   R.id("*")
        // 字符串替换逻辑，替换data中的所有from为to
        private String replaceLogic(String data, String from, String to)
        {
            String tmp = data;
            if (!from.Contains("*") && !to.Contains("*")) tmp = tmp.Replace(from, to);
            else if (from.Contains("*") && to.Contains("*"))
            {
                tmp = replace(tmp, from, to);
            }
            else MessageBox.Show("此功能待实现！");

            return tmp;
        }
        // R.id.*   R.id("*")
        // 字符串替换逻辑，替换data中的所有from为to
        private String replaceLogic0(String data, String from, String to)
        {
            String tmp = data;
            if (!from.Contains("*") && !to.Contains("*")) tmp = tmp.Replace(from, to);
            else if (from.Contains("*") && to.Contains("*"))
            {
                tmp = replace(tmp, from + ")", to);
                tmp = replace(tmp, from + "}", to);
                tmp = replace(tmp, from + ",", to);
                tmp = replace(tmp, from + ";", to);
            }
            else MessageBox.Show("此功能待实现！");

            return tmp;
        }
        // int[] ids = { R.id.music, R.id.about, R.id.more, R.id.help /* , R.id.CDKey */};
        // R.id.*,   R.id("*")
        // 字符串替换逻辑，替换data中的所有from = "R.id.*,"为to = "R.id("*"),"
        private String replace(String data, String from, String to)
        {
            String tmp = data;

            String[] fStr = from.Split('*');
            String[] tStr = to.Split('*');

            int index1 = 0;
            while (tmp.Substring(index1).Contains(fStr[0]))
            {
                // 前缀索引
                int index1Tmp = tmp.IndexOf(fStr[0], index1);
                if (index1Tmp > index1) index1 = index1Tmp;

                // 后缀索引
                String c = fStr[1];
                int index2 = tmp.IndexOf(c, index1 + fStr[0].Length);
                if (c.Equals(""))
                {
                    // 默认后缀，取较小的分隔符索引为后缀索引
                    String[] sp = { ")", "}", ",", ";", " " };

                    for (int i = 0; i < sp.Length; i++)
                    {
                        int I = tmp.IndexOf(sp[i], index1 + fStr[0].Length);
                        if (index2 == -1 || (index2 > I && I != -1))
                        {
                            index2 = I;
                            c = sp[i];
                        }
                    }
                }
                if (index2 == -1) continue;


                String fromStr = tmp.Substring(index1, index2 - index1).Replace(c, "").TrimEnd();  // 源串
                index1 += fStr[0].Length;
                String arg = tmp.Substring(index1, index2 - index1).Replace(c, "").TrimEnd();      // 获取*对应的字符串

                String toStr = tStr[0] + arg + tStr[1];     // 目标串
                //tmp = tmp.Replace(fromStr, toStr);          // 替换为目标串
                tmp = tmp.Replace(fromStr + c, toStr + c);  // 替换为目标串(仅替换全字匹配的串）
            }

            return tmp;
        }

        // int[] ids = { R.id.music, R.id.about, R.id.more, R.id.help /* , R.id.CDKey */};
        // R.id.*,   R.id("*")
        // 字符串替换逻辑，替换data中的所有from = "R.id.*,"为to = "R.id("*"),"
        private String replace0(String data, String from, String to)
        {
            String tmp = data;

            String[] fStr = from.Split('*');
            String[] tStr = to.Split('*');

            while (tmp.Contains(fStr[0]))
            {
                int index1 = tmp.IndexOf(fStr[0]);                          // 前缀索引
                int index2 = tmp.IndexOf(fStr[1], index1 + fStr[0].Length); // 后缀索引
                int index3 = tmp.IndexOf(' ', index1 + fStr[0].Length);     // 后缀之前有空' '则取其索引
                if (index3 != -1 && index3 < index2) index2 = index3;
                else if (index2 == -1 && index3 != -1) index2 = index3;
                else if (index2 == -1 && index3 == -1) continue;

                String fromStr = tmp.Substring(index1, index2 - index1).Replace(fStr[1], "").TrimEnd();  // 源串
                index1 += fStr[0].Length;
                String arg = tmp.Substring(index1, index2 - index1).Replace(fStr[1], "").TrimEnd();      // 获取*对应的字符串

                String toStr = tStr[0] + arg + tStr[1];                     // 目标串
                tmp = tmp.Replace(fromStr + fStr[1], toStr + fStr[1]);      // 替换为目标串(仅替换全字匹配的串）
            }

            return tmp;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            String data = "";
            foreach (String fileName in OpendFilesName)
            {
                //String data = T.ToString(fileName);
                data = T.ToString(fileName);    // 获取文件数据

                // 自定义替换逻辑
                data = replaceLogic(data, "com.joym.BigSonGoCart.R", "com.shjc.jsbc.view2d.util.R");
                data = replaceLogic(data, "R.id.*", "R.id(\"*\")");
                data = replaceLogic(data, "R.drawable.*", "R.drawable(\"*\")");
                data = replaceLogic(data, "R.layout.*", "R.layout(\"*\")");
                data = replaceLogic(data, "R.raw.*", "R.raw(\"*\")");
                data = replaceLogic(data, "R.string.*", "R.string(\"*\")");
                data = replaceLogic(data, "R.style.*", "R.style(\"*\")");
                data = replaceLogic(data, "R.menu.*", "R.menu(\"*\")");
                data = replaceLogic(data, "R.anim.*", "R.anim(\"*\")");
                data = replaceLogic(data, "R.array.*", "R.array(\"*\")");
                data = replaceLogic(data, "R.attr.*", "R.attr(\"*\")");


                //MessageBox.Show("替换逻辑完成!\n" + data);
                T.SaveToNativeFile(data, fileName, true);
            }
            MessageBox.Show("替换逻辑完成!");
        }

        private String[] tmpData = { "R.id.*", "R.id(\"*\")", "com.joym.BigSonGoCart.R", "com.shjc.jsbc.view2d.util.R" };
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                tmpData[0] = textBox1.Text;
                tmpData[1] = textBox2.Text;
                textBox1.Text = tmpData[2];
                textBox2.Text = tmpData[3];
            }
            else
            {
                tmpData[2] = textBox1.Text;
                tmpData[3] = textBox2.Text;
                textBox1.Text = tmpData[0];
                textBox2.Text = tmpData[1];
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            //String R = T.ToString(OpendFilesName[0]);
            // 获取R文件信息
            String tmp = Data.R_java;
            if (textBox1.Text.Contains(".R") && textBox2.Text.Contains(".R"))
            {
                String fromPak = textBox1.Text, toPak = textBox2.Text;
                fromPak = fromPak.Substring(0, fromPak.LastIndexOf(".R"));
                toPak = toPak.Substring(0, toPak.LastIndexOf(".R"));

                tmp = tmp.Replace("com.joym.BigSonGoCart", fromPak);
                tmp = tmp.Replace("com.shjc.jsbc.view2d.util", toPak);
            }


            // 根据所有载入的文件，判定生成R文件保存路径
            string CurDir = getDir();
            if (CurDir.Equals("")) CurDir = System.AppDomain.CurrentDomain.BaseDirectory;
            CurDir += "R.java";

            // 导出R文件
            T.SaveToNativeFile(tmp, CurDir, true);
            T.MessageWithOpen("成功导出R.java", CurDir);
        }

        private string getDir()
        {
            String tmp = textBox2.Text;
            if (tmp.EndsWith(".R"))
            {
                tmp = tmp.Substring(0, tmp.LastIndexOf(".R"));
                tmp = tmp.Replace('.', '\\');
            }
            else return "";

            if (OpendFilesName == null) return "";
            foreach (String fileName in OpendFilesName)
            {
                if (fileName.Contains(tmp))
                {
                    tmp = fileName.Substring(0, fileName.LastIndexOf(tmp)) + tmp + "\\";
                    return tmp;
                }
            }

            return "";
        }

        // 逆向替换逻辑
        private void button4_Click(object sender, EventArgs e)
        {
            String data = "";
            foreach (String fileName in OpendFilesName)
            {
                //String data = T.ToString(fileName);
                data = T.ToString(fileName);    // 获取文件数据

                // 自定义替换逻辑
                data = replaceLogic(data, "com.shjc.jsbc.view2d.util.R", "com.joym.BigSonGoCart.R");
                data = replaceLogic(data, "R.id(\"*\")", "R.id.*");
                data = replaceLogic(data, "R.drawable(\"*\")", "R.drawable.*");
                data = replaceLogic(data, "R.layout(\"*\")", "R.layout.*");
                data = replaceLogic(data, "R.raw(\"*\")", "R.raw.*");
                data = replaceLogic(data, "R.string(\"*\")", "R.string.*");
                data = replaceLogic(data, "R.style(\"*\")", "R.style.*");
                data = replaceLogic(data, "R.menu(\"*\")", "R.menu.*");
                data = replaceLogic(data, "R.anim(\"*\")", "R.anim.*");
                data = replaceLogic(data, "R.array(\"*\")", "R.array.*");
                data = replaceLogic(data, "R.attr(\"*\")", "R.attr.*");


                //MessageBox.Show("替换逻辑完成!\n" + data);
                T.SaveToNativeFile(data, fileName, true);
            }
            MessageBox.Show("替换逻辑完成!");
        }

        private void label3_Click(object sender, EventArgs e)
        {
            //String CurDir = System.AppDomain.CurrentDomain.BaseDirectory;
            //CurDir += "R.java";

            //// 导出R文件
            //T.SaveToNativeFile(Data.tools, CurDir + "Tools.cs", true);
            //T.SaveToNativeFile(Data.form1, CurDir + "Form1.cs", true);
            //T.SaveToNativeFile(Data.form_design, CurDir + "Form1.Designer.cs", true);
            //T.MessageWithOpen("成功导出R.java", CurDir);
        }
    }
}

